import { KeyboardEvent } from './event'
import {SelectionModel,SelectionType,TextModel} from './models'
import { InsertTextOperation,SetSelectionOperation,RemoveTextOperation } from './operations'
import {RenderView} from './view'
interface Operation {
    apply(editor: Editor): void;
}
class Editor {
    container: HTMLElement 
    eventHandler!: KeyboardEvent
    selectionModel_: SelectionModel | null = null
    textModel_: TextModel | null = null
    view_: RenderView | null = null;
    constructor(container:HTMLElement ){
        this.container = container
    }
    apply(operation:Operation){
        operation.apply(this)
    }
    getTextModel() : TextModel | null {
        return this.textModel_;
    }
    getSelectionModel() : SelectionModel | null {
        return this.selectionModel_;
    }
    init(){//拦截浏览器默认事件 创建edit模型
        this.textModel_ = new TextModel();
        this.selectionModel_ = new SelectionModel()
        this.view_ = new RenderView(this.textModel_,this.container,this.selectionModel_)
        this.eventHandler = new KeyboardEvent(this,this.container,this.view_)
        this.eventHandler.addListeners()
    }
    insertTextAtCursor(text:string){
        const selection: SelectionType  = this.selectionModel_!.getSelection()!
        let startIndex = selection.anchor
        if(!this.selectionModel_?.isCollapsed()){
            const removeTextOperation = new RemoveTextOperation(selection!.anchor, selection!.focus)
            this.apply(removeTextOperation)
            if(this.selectionModel_?.isBackward()){
                startIndex = selection.focus;
            }
        }
        let cursorIndex = startIndex + text.length
        const insertTextOperation = new InsertTextOperation(text,startIndex)
        this.apply(insertTextOperation)
        this.setSelection(cursorIndex, cursorIndex)
    }
    deleteTextAtCursor(){
        const selection: SelectionType  = this.selectionModel_!.getSelection()!
        console.log(selection)
        let startIndex = selection.anchor
        if(!this.selectionModel_?.isCollapsed()){
            const removeTextOperation = new RemoveTextOperation(selection!.anchor, selection!.focus)
            this.apply(removeTextOperation)
            if(this.selectionModel_?.isBackward()){
                startIndex = selection.focus;
            }
        } else if(startIndex > 0){
            const removeTextOperation = new RemoveTextOperation(selection!.anchor-1, selection!.focus)
            this.apply(removeTextOperation)
            startIndex--

            }
       
        this.setSelection(startIndex, startIndex)

    }
    setSelection(anchor: number, focus: number){
        const selectionOperaction = new SetSelectionOperation({anchor, focus})
        this.apply(selectionOperaction)
    }
      


}
export default Editor